--[[
    Author          ZhengFeng
    Time            2020.12.08
    Description     宠物申请界面-我的申请
]]--

require "Common/define"
require "Logic/PetManager"
local Page_PetApplyMyRequest = UIBase.New(PanelResNames.Page_PetApplyMyRequest)
local this = Page_PetApplyMyRequest
local MyRequestType = {
    Request = 0,
    Undo = 1,
}
local PetMatingType = {
    NoAdd = 0,
    OthersPet = 1,
    MyPet = 2,
}

function this:Init()
    UIBase.Init(this)
end

function this:OnCreate()
    self.Btn_BGClose = self:GetChild("Btn_BGClose")
    self:RegisterOnClick(self.Btn_BGClose, self.onClickClose)
    self.Btn_Back = self:GetChild("Btn_Back")
    self:RegisterOnClick(self.Btn_Back, self.onClickClose)

    self.Txt_PanelTitle = self:GetChild("title")
    self.Combo_Template = self:GetChild("Combo_Template")
    self.Model_TemplatePet = self.Combo_Template:GetChild("Model_Pet")
    self.Combo_Mutate = self:GetChild("Combo_Mutate")
    self.Model_MutatePet = self.Combo_Mutate:GetChild("Model_Pet")
    self:RegisterOnClick(self.Combo_Mutate, self.onClickMutate)
    self.MyRequestController = self:GetController("MyRequestType")
    self.List_ChangePart = self:GetChild("List_ChangePart");
    self.titleText = self:GetChild("title1");

    --申请
    self.Img_PetBaby = self:GetChild("Img_PetBaby")
    self.Btn_Request = self:GetChild("Btn_Request")
    self.isChoosePetController = self:GetController("isChoosePet");
    self:RegisterOnClick(self.Btn_Request, self.onClickRequest)
    self.Btn_Request:GetChild("title").text = getLanguage("PetMating_Btn_Mutate")
    self.Btn_Preview = self:GetChild("Btn_Preview")
    self.Btn_Preview:GetChild("title").text = getLanguage("PetMating_Btn_Preview")
    self:RegisterOnClick(self.Btn_Preview, self.onClickPreview)
    self:GetChild("Txt_TypeName").text = getLanguage("PetMating_Txt_MutatePet")

    --撤销
    self.head = self:GetChild("head");
    self.Txt_Time = self:GetChild("Txt_Time")
    self.Btn_Undo = self:GetChild("Btn_Undo")
    self.Txt_Tips = self:GetChild("name");
    self:RegisterOnClick(self.Btn_Undo, self.onClickUndo)


end

function this:OnEnable()
    ListenEvent(Config.EventType.RefreshPetCancelMating, self.onRefreshPetCancelMating, self)
    ListenEvent(Config.EventType.SelectPet, self.onChangeSelectedPet, self)
    ListenEvent(Config.EventType.RefreshMyApply, self.onRefreshMyApply, self)

    ListenEvent(Config.EventType.RefreshOtherPetInfo, self.onRefreshOtherPetInfo, self)
    ListenEvent(Config.EventType.FresPetPage, this.showPanel)
    this.lockMoneys = 0;
    PetManager.lockParts = {};
    this:showPanel()
end

function this:OnDisable()
    this:removeTimer()
    this:removeTeamplatePetModel()
    this:removeMutatePetModel()
    PetManager.TemplatePetId = 0;
    PetManager.MutatePetId = 0;
    CloseEvent(Config.EventType.RefreshPetCancelMating, self.onRefreshPetCancelMating, self)
    CloseEvent(Config.EventType.SelectPet, self.onChangeSelectedPet, self)
    CloseEvent(Config.EventType.RefreshMyApply, self.onRefreshMyApply, self)
    CloseEvent(Config.EventType.RefreshOtherPetInfo, self.onRefreshOtherPetInfo, self)
    CloseEvent(Config.EventType.FresPetPage, this.showPanel)
end
function this:OnDestroy()
    this:OnDisable()
end

function this:onClickClose()
    FireEvent(Config.EventType.Fresh_MyFriendPetInfo);
    friendHandler.ReqFriendData()
    DestoryUI(PanelResNames.Page_PetApplyMyRequest)
end
function this:showPanel()
    if table.getn(PetManager.myApply) > 0 then
        this:showUndoPanel()
        this:setTimer()
        this:showTemplatePetModel()
        this:showMutatePetModel()
    elseif table.getn(PetManager.OtherPetInfo) > 0 then
        this:removeTimer()
        this:showRequestPanel()
        this:showTemplatePetModel()
        this:showMutatePetModel()
    end
    this.titleText.text = 0;

end

function this:onRefreshPetCancelMating()
    this:onClickClose()
end
function this:onChangeSelectedPet()
    this:showPanel()
end
function this:onRefreshMyApply()
    this:showPanel()
end
function this:onRefreshOtherPetInfo()
    this:showPanel()
end

--申请界面
function this:showRequestPanel()
    self.Txt_PanelTitle.text = getLanguage("PetApply_RequestTitle") --"我的申请"
    self.MyRequestController:SetSelectedIndex(MyRequestType.Request)
    self.Combo_Template:GetController("PetMatingType"):SetSelectedIndex(PetMatingType.OthersPet)
    self.Combo_Template:GetChild("Txt_MatingType").text = getLanguage("PetMating_MutateTitle") --"模板体"
    self.Combo_Template:GetChild("Txt_PlayerName").text = PetManager.OtherPetInfo.playerName--"拟变体"
    self.Combo_Template:GetChild("head"):GetChild("head"):GetChild("HeadIcon").url = SkinManager.GetHeroIconBySkinId(PetManager.OtherPetInfo.pic)
    self.Combo_Template:GetChild("head"):GetChild("frame").url = "ui://ICONAtlas/" ..  (PetManager.OtherPetInfo.picFrame ~= nil and PetManager.OtherPetInfo.picFrame or PetManager.OtherPetInfo.frame)
    self.Combo_Template:GetChild("Txt_PetName").text = PetManager.OtherPetInfo.petName
    self.Combo_Template:GetChild("PetLevel").text = "";
    local _selectedIndex = PetMatingType.NoAdd
    if PetManager.MutatePetId ~= 0 then
        _selectedIndex = PetMatingType.MyPet
        local _petInfo = PetManager.GetPetInfoByPetId(PetManager.MutatePetId)
        self.Combo_Mutate:GetChild("Txt_PetName").text = _petInfo.petName
    end
    self.Combo_Mutate:GetChild("Txt_MatingType").text = getLanguage("PetMating_TemplateTitle") --"拟变体"
    self.Combo_Mutate:GetController("PetMatingType"):SetSelectedIndex(_selectedIndex)
    self.Combo_Mutate:GetChild("PetLevel").text = getLanguage("PetMerge_Level") .. PetManager.EvoLevel;

    local _touchable = PetManager.MutatePetId ~= 0 and PetManager.OtherPetInfo.petId ~= 0
    self.Btn_Preview.touchable = _touchable
    self.Btn_Preview.enabled = _touchable
    self.Btn_Request.touchable = _touchable
    self.Btn_Request.enabled = _touchable
end
function this:onClickMutate()
    if table.getn(PetManager.myApply) > 0 then
        return
    end
    PetManager.IsTemplatePet = false
    showUI(PanelNames.PetSelect, self)
end
function this:onClickRequest()
    if table.getn(PetManager.OtherPetInfo) > 0 then
        if BrokerManager.DetailSelectedPetId ~= 0 then
            local _brokerManagerPetInfo = BrokerManager.GetPetInfoByPetId(BrokerManager.DetailSelectedPetId,2)
            local _petmanagerPetInfo = PetManager.GetPetInfoByPetId(PetManager.MutatePetId)
            if BrokerManager.CheckIsMyPlayer(_brokerManagerPetInfo.playerId) then
                UISysTips.AddMsg(getLanguage("PETSHOP_EvolutionPetIsMineError"))
            else
                local _lockParts = {};
                for i, v in pairs(PetManager.lockParts) do
                    table.insert(_lockParts, v.type);
                end
                if self.lockMoneys > logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD) then
                    UISysTips.AddMsg(getLanguage("ErrorCode_3412"));
                elseif PetManager.GetPetItemType(_petmanagerPetInfo) == PetManager.PetItemType.MatingCD then 
                    UISysTips.AddMsg(getLanguage("PETSHOP_PetMatingEndTimeError"))         --虚弱状态下的宠物不能进化
                elseif _petmanagerPetInfo.IsLocked then
                    UISysTips.AddMsg(getLanguage("PETSHOP_PetLockError"))                   --锁定状态下的宠物不能进化
                else
                    
                    BrokerHandler.ReqBrokerPetEvolution(_brokerManagerPetInfo.goodsId,PetManager.MutatePetId,_lockParts)
                    PetManager.Track_evolvePet(_brokerManagerPetInfo.playerId, _brokerManagerPetInfo.genes)
                end
            end
            return
        end
        local friendInfo = FriendManager.GetMyFriend(PetManager.OtherPetInfo.playerId)
        if friendInfo.petInfo== nil then
            return
        end
        if  PetManager.OtherPetInfo.petId ~= friendInfo.petInfo.petId then
            UISysTips.AddMsg(getLanguage("PetApply_Change"));
            self.onClickClose()
        else
            local sendLockParts = {};
            for i, v in pairs(PetManager.lockParts) do
                table.insert(sendLockParts, v.type);
            end
            if self.lockMoneys <= logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.GOLD) then
                PetHandler.ReqAskMating(PetManager.OtherPetInfo.playerId, PetManager.OtherPetInfo.petId, PetManager.MutatePetId,nil,sendLockParts)
            else
                UISysTips.AddMsg(getLanguage("ErrorCode_3412"));
            end
        end
    end
end
function this:onClickPreview()
    if PetManager.MutatePetId ~= 0 and PetManager.OtherPetInfo.petId ~= 0 then
        showUI(PanelNames.Page_PetMatingPreview)
    end
end

--撤销界面
function this:showUndoPanel()
    self.Txt_PanelTitle.text = getLanguage("PetApply_UndoTitle") --"申请撤销"
    self.MyRequestController:SetSelectedIndex(MyRequestType.Undo)
    self.lastTime = PetManager.myApply.endTime - HelperFunc.GetServerTime()
    if self.lastTime < 0 then
        self.lastTime = 0
    end
    self.Txt_Time.text = TimeFormatToHHMMSS(self.lastTime)

    self.Combo_Template:GetController("PetMatingType"):SetSelectedIndex(PetMatingType.OthersPet)
    self.Combo_Template:GetChild("Txt_MatingType").text = getLanguage("PetMating_TemplateTitle") --"模板体"
    self.Combo_Template:GetChild("Txt_PlayerName").text = PetManager.myApply.toPlayerName
    self.Combo_Template:GetChild("Txt_PetName").text = PetManager.myApply.templatePetInfo.petName
    self.head:GetChild("head"):GetChild("HeadIcon").url = EnumConst.AtlasPath.ICONAtlas .. dataTable.getRow("t_hero", PetManager.OtherPetInfo.pic)["f_HeroIcon"];
    self.Combo_Template:GetChild("head"):GetChild("head"):GetChild("HeadIcon").url = EnumConst.AtlasPath.ICONAtlas .. dataTable.getRow("t_hero", PetManager.OtherPetInfo.pic)["f_HeroIcon"];
    self.Combo_Template:GetChild("head"):GetChild("frame").url = "ui://ICONAtlas/" ..  (PetManager.OtherPetInfo.picFrame ~= nil and PetManager.OtherPetInfo.picFrame or PetManager.OtherPetInfo.frame)
    self.Combo_Template:GetChild("PetLevel").text = "";
    self.Txt_Tips.text = PetManager.myApply.toPlayerName;
    self.Combo_Mutate:GetController("PetMatingType"):SetSelectedIndex(PetMatingType.MyPet)
    self.Combo_Mutate:GetChild("Txt_MatingType").text = getLanguage("PetMating_MutateTitle") --"拟变体"
    self.Combo_Mutate:GetChild("Txt_PetName").text = PetManager.myApply.mutatePetInfo.petName
    self.Combo_Mutate:GetChild("PetLevel").text = getLanguage("PetMerge_Level") .. PetManager.EvoLevel;
end
function this:onClickUndo()
    -- if table.getn(PetManager.myApply) > 0 then
    --     PetHandler.ReqCancelMating(PetManager.myApply.templatePetInfo.petId, PetManager.myApply.mutatePetInfo.petId)
    -- end
end
function this:setTimer()
    if self.petTimer == nil then
        self.petTimer = utimer.timeCall(function()
            self.lastTime = self.lastTime - 1
            if self.lastTime < 0 then
                self.lastTime = 0
                this:removeTimer()
                this:onClickClose()
            end
            self.Txt_Time.text = TimeFormatToHHMMSS(self.lastTime)
        end, 1000, -1)
    end
end
function this:removeTimer()
    if self.petTimer then
        utimer.remove(self.petTimer)
        self.petTimer = nil
    end
end

--显示宠物模型
function this:removeTeamplatePetModel()
    if self.TemplatePetModelGO then
        destroy(self.TemplatePetModelGO)
    end
    self.TemplatePetModelGO = nil
end
function this:removeMutatePetModel()
    if self.MutatePetModelGO then
        destroy(self.MutatePetModelGO)
    end
    self.MutatePetModelGO = nil
end

function this:showTemplatePetModel()
    local _petInfo = nil
    if table.getn(PetManager.myApply) > 0 then
        _petInfo = PetManager.myApply.templatePetInfo
    elseif table.getn(PetManager.OtherPetInfo) > 0 then
        _petInfo = PetManager.OtherPetInfo
    end
    if _petInfo and #_petInfo.genes == PetManager.PetPart.Ornament then
        local _petModelInfo = {}
        _petModelInfo.parentGO = self.Model_TemplatePet
        _petModelInfo.petId = _petInfo.petId
        if self.TemplatePetModelGO and self.TemplateGoWrapper then
            _petModelInfo.modelGO = self.TemplatePetModelGO
            _petModelInfo.modelWrapper = self.TemplateGoWrapper
            PetManager.PetModelRefresh(_petModelInfo, _petInfo.genes, true)
        else
            this:removeTeamplatePetModel()
            resMgr:LoadModelPrefab(PetManager.PetModelPrefab, function(go)
                self.TemplatePetModelGO = newObject(go)

                local com = self.TemplatePetModelGO:GetComponent("SkeletonGraphic")

                if self.TemplatePetModelGO and com then
                    com.material = resMgr.Pet_Copy_Mat
                    com.material:SetFloat("_StencilComp",8)
                    com.material:SetFloat("_Stencil",1);
                end

                local _modelWrapper = self.TemplateGoWrapper
                self.TemplateGoWrapper = GoWrapper.New()
                _petModelInfo.modelGO = self.TemplatePetModelGO
                _petModelInfo.modelWrapper = self.TemplateGoWrapper
                PetManager.PetModelFirstSet(_petModelInfo, _petInfo.genes, true, Vector3.New(0, 0, 0), Vector3.New(1.2, 1.2, 1))
                if _modelWrapper then
                    _modelWrapper:Dispose()
                end
            end)
        end
    end
end
function this:showMutatePetModel()
    --if PetManager.MutatePetId == 0 then
    --    return
    --end
    local _petInfo = nil
    if table.getn(PetManager.myApply) > 0 then
        _petInfo = PetManager.myApply.mutatePetInfo
    elseif PetManager.MutatePetId ~= 0 then
        _petInfo = PetManager.GetPetInfoByPetId(PetManager.MutatePetId)
    end

    if _petInfo and #_petInfo.genes == PetManager.PetPart.Ornament then
        local _petModelInfo = {}
        if PetManager.MutatePetId ~= 0 then
            self.List_ChangePart.itemRenderer = self.rendererPart;
            self.List_ChangePart.numItems = #_petInfo.genes;
            self.isChoosePetController.selectedIndex = 1;
        else
            self.isChoosePetController.selectedIndex = 0;
        end
        _petModelInfo.parentGO = self.Model_MutatePet
        _petModelInfo.petId = _petInfo.petId
        if self.MutatePetModelGO and self.MutateGoWrapper then
            _petModelInfo.modelGO = self.MutatePetModelGO
            _petModelInfo.modelWrapper = self.MutateGoWrapper
            PetManager.PetModelRefresh(_petModelInfo, _petInfo.genes, true)
        else
            this:removeMutatePetModel()
            resMgr:LoadModelPrefab(PetManager.PetModelPrefab, function(go)
                self.MutatePetModelGO = newObject(go)

                local com = self.MutatePetModelGO:GetComponent("SkeletonGraphic")

                if self.MutatePetModelGO and com then
                    com.material = resMgr.Pet_Copy_Mat
                    com.material:SetFloat("_StencilComp",8)
                    com.material:SetFloat("_Stencil",1);
                end

                _petModelInfo.modelGO = self.MutatePetModelGO
                local _modelWrapper = self.MutateGoWrapper
                self.MutateGoWrapper = GoWrapper.New()
                _petModelInfo.modelWrapper = self.MutateGoWrapper
                PetManager.PetModelFirstSet(_petModelInfo, _petInfo.genes, true, Vector3.New(0, 0, 0), Vector3.New(1.2, 1.2, 1))
                if _modelWrapper then
                    _modelWrapper:Dispose()
                end
            end)
        end
    else
        self.isChoosePetController.selectedIndex = 0;
    end
end

function this.rendererPart(idx, obj)
    local lockController = obj:GetController("isLock");
    lockController.selectedIndex = PetManager.checkTypeIsCheck(idx + 1) and 1 or 0;
    local _petInfo = PetManager.GetPetInfoByPetId(PetManager.MutatePetId)
    this:initParts(obj, _petInfo.genes[idx + 1]);
end

function this:initParts(go, data)
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.PetPartItem);
    ctrlItem.initData(go, data,function(cfg)
        self.lockPart(cfg, go)
        local moneys = decodeJsonStrToTabel(G.dataTable["t_global"]["232"]["f_string_value"])
        self.lockMoneys = moneys[table.getn(PetManager.lockParts)] or 0;
        this.titleText.text = self.lockMoneys;
    end)
end

function this.lockPart(cfg, obj)
    local id = cfg.f_GeneId
    if id == nil then
        return
    end

    local lockController = obj:GetController("isLock");
    if PetManager.lockParts == nil then
        PetManager.lockParts = {};
    end
    if PetManager.lockParts[id] == nil then
        --锁定
        if table.getn(PetManager.lockParts) >= table.getn(decodeJsonStrToTabel(G.dataTable["t_global"]["232"]["f_string_value"])) then
            UISysTips.AddMsg(getLanguage("PetApply_LockFull")) --已经锁定了12个部位
            return
        end
        local data = {}
        data.id = id;
        data.type = cfg.f_ChromosomeId;
        PetManager.lockParts[id] = data;
        lockController.selectedIndex = 1;
    else
        --解除锁定
        PetManager.lockParts[id] = nil;
        lockController.selectedIndex = 0;
    end
    --table.insert(PetManager.lockParts ,id);

end

return this